package model.factories.controlflow;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Pattern;
import model.Interpreter;
import model.SyntaxErrorException;
import model.commands.Command;
import model.commands.controlflow.ForCommand;
import model.factories.CommandFactory;


/**
 * A factory used to create ForCommand objects.
 * 
 * @author Erick Gonzalez
 */
public class ForCommandFactory extends CommandFactory {

    private static final String REPEAT_KEYWORD = "REPEAT";
    private static final String FOR_KEYWORD = "FOR";

    private final Pattern myForPattern = Pattern.
            compile(getInterpreter().getLanguage().getString("ForCommandPattern"));
    
        
    /**
     * 
     * @param interpreter an interpreter
     */
    public ForCommandFactory (Interpreter interpreter) {
        super(interpreter);
    }

    @Override
    public Command createCommand (Scanner commandReader,
                                  Map<String, Integer> variables) throws SyntaxErrorException {
        // read the command name
        String commandName = commandReader.next();
        String variable;
        int start;
        int end;
        int increment;
        if (commandName.equals(REPEAT_KEYWORD)) {
            variable = ":repcount";
            start = 1;
            end = commandReader.nextInt() + 1;
            increment = 1;
        }
        else {
            // read first open bracket
            commandReader.next();
            variable = commandReader.next();
            if (commandName.equals(FOR_KEYWORD)) {
                start = commandReader.nextInt();
                end = commandReader.nextInt();
                increment = commandReader.nextInt();
            }
            else {
                start = 0;
                end = commandReader.nextInt();
                increment = 1;
            }

            // read first closing bracket
            commandReader.next();
        }
        StringBuilder commandStringBuilder = new StringBuilder();
        while (!commandReader.hasNext("]")) {
            commandStringBuilder.append(commandReader.next() + " ");
        }
        commandStringBuilder.append(commandReader.next());
        Map<String, Integer> newVariables = new HashMap<String, Integer>(variables);
        return new ForCommand(getInterpreter(), newVariables, commandStringBuilder.toString(),
                              variable, start, end, increment);
    }

    @Override
    public Pattern patternToMatch () {
        return myForPattern;
    }
}
